const express = require("express");
const cors = require("cors");
const ollama = require("ollama");
require("dotenv").config();

const app = express();
app.use(cors()); // 允许跨域
app.use(express.json());

const MODEL_NAME = "deepseek-r1:8b"; // 确认模型名称匹配

app.post("/chat", async (req, res) => {
  try {
    const response = await ollama.chat({
      model: MODEL_NAME,
      prompt: req.body.prompt,
      stream: req.body.stream || false, // 非流式响应
      options: {
        temperature: 0.7, // 创造性（0-1，越高越随机）
        max_tokens: 1000, // 最大输出长度
        top_p: 0.9, // 采样阈值
        repeat_penalty: 1.2, // 重复惩罚系数
      },
    });

    res.json({ content: response.message.content });
  } catch (error) {
    console.error("Ollama API error:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

const PORT = 3001;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
